package com.tt.payee.controller.login;

import com.google.common.collect.Maps;

import com.tt.payee.api.ResponseResult;
import com.tt.payee.api.ResultCode;
import com.tt.payee.business.AbortException;
import com.tt.payee.business.BusinessException;
import com.tt.payee.business.BusinessStatus;
import com.tt.payee.common.Constant;
import com.tt.payee.domain.TbUser;
import com.tt.payee.service.login.TbUserService;
import com.tt.payee.utils.JwtTokenUtil;
import com.tt.payee.utils.RedisUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * @author zhaochongsen
 * @Description: 后台用户登录
 * @date:2020-06-05 11:01
 */
@RestController
@RequestMapping("/consumer/auth")
@Slf4j
public class LoginController {

    @Autowired
    TbUserService userService;

    @Autowired
    private RedisUtils redisUtils;
    /**
     * 登录接口
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(value = "用户登录", notes = "根据用户名、密码判断该用户是否存在")
    @ApiResponses({
            @ApiResponse(code = 200, message = "登录成功"),
            @ApiResponse(code = 500, message = "用户已被停用,请联系管理员"),
            @ApiResponse(code = 100101, message = "管理员账号密码错误")
    })
    public ResponseResult<Object> login(@RequestBody TbUser tbUser) {
        // 返回结果
        Map<String, Object> result = Maps.newHashMap();

        if(StringUtils.isBlank(tbUser.getUsername()) || StringUtils.isBlank(tbUser.getPassword())){
            throw new AbortException("账号密码不能为空");
        }

        TbUser user = userService.getOne(tbUser);

        if (user == null) {
            throw new BusinessException(BusinessStatus.ADMIN_PASSWORD);
        }

        if (user.getStatus().equals(Constant.USER_STATUS_CLOSE)) {
            return ResponseResult.failed("用户已被停用,请联系管理员");
        }

        if (user.getStatus().equals(Constant.USER_STATUS_DELETE)) {
            return ResponseResult.failed("对不起,您的账号不存在");
        }

        String token = JwtTokenUtil.generateBackendUserToken(user);
        result.put("token", token);

        user = userService.getByIdWithPermission(user.getUserId());
        user.setPassword(null);
        result.put("user",user);

        redisUtils.set(Constant.BACKEND_TOKEN_PRE+":"+user.getUserId(), token, Constant.EXPIRATION_TIME);

        return ResponseResult.success("登录成功", result);

    }

    /**
     * 刷新用户token
     *
     * @return
     */
    @RequestMapping(value = "/refreshToken", method = RequestMethod.POST)
    @ApiOperation(value = "刷新用户token")
    public ResponseResult<Object> refreshToken(HttpServletRequest exchange) throws Exception {

        // 获取 token
        String token = exchange.getHeader("access_token");
        Long id = Long.parseLong(JwtTokenUtil.getIdFromToken(token));
        TbUser user = userService.getByIdWithPermission(id);
        user.setPassword(null);

        // 新生成token并返回数据
        Map<String, Object> result = Maps.newHashMap();
        result.put("user",user);
        String newToken = JwtTokenUtil.generateBackendUserToken(user);
        result.put("token", newToken);
        redisUtils.set(Constant.BACKEND_TOKEN_PRE+":"+user.getUserId(), newToken, Constant.EXPIRATION_TIME);

        return new ResponseResult<>(ResultCode.SUCCESS.getCode(), "操作成功", result);
    }

    /**
     * 注销账号
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ApiOperation(value = "管理员注销账号")
    public ResponseResult<Object> logout(HttpServletRequest exchange) throws Exception {

        // 获取 token
        String token = exchange.getHeader("access_token");
        // 删除 token 以注销
        redisUtils.del(Constant.BACKEND_TOKEN_PRE+":"+JwtTokenUtil.getIdFromToken(token));
        return ResponseResult.success("注销成功");

    }

}
